import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';

import '/app/utils/local_file_utils.dart';
import 'video_list_page.dart';

// 控制器类，负责管理视频文件夹数据
class FolderController extends GetxController {
  var hasPermission = false.obs; // 观察权限状态
  var paths = <AssetPathEntity>[].obs; // 文件夹路径列表

  @override
  void onInit() {
    super.onInit();
    checkPermission(); // 检查权限
  }

  // 请求权限
  Future<void> requestPermission() async {
    await LocalFileUtils.requestPermission();
    hasPermission.value = await LocalFileUtils.checkPermission();
    if (hasPermission.value) {
      getVideoFolders(); // 获取视频文件夹
    }
  }

  // 检查权限
  Future<void> checkPermission() async {
    hasPermission.value = await LocalFileUtils.checkPermission();
    if (hasPermission.value) {
      getVideoFolders(); // 获取视频文件夹
    }
  }

  // 获取视频文件夹
  Future<void> getVideoFolders() async {
    paths.value = await LocalFileUtils.getVideoFolders();
  }
}

// 页面1：视频文件夹列表页面
class VideoFolderListPage extends StatelessWidget {
  final FolderController folderController = Get.put(FolderController());

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Obx(() {
        // 权限未授权
        if (!folderController.hasPermission.value) {
          return Center(
            child: ElevatedButton(
              onPressed: () async {
                await folderController.requestPermission();
              },
              child: Text('去授权'),
            ),
          );
        }

        // 未找到文件夹
        if (folderController.paths.isEmpty) {
          return Center(
            child: ElevatedButton(
              onPressed: () async {
                await folderController.getVideoFolders();
              },
              child: Text('没有找到文件夹，重新扫描'),
            ),
          );
        }

        // 展示文件夹列表
        return ListView.builder(
          itemCount: folderController.paths.length,
          itemBuilder: (BuildContext context, int index) {
            AssetPathEntity folder = folderController.paths[index];

            return FutureBuilder<int>(
              future: folder.assetCountAsync,
              builder: (context, snapshot) {
                final videoCount = snapshot.data ?? 0;

                return ListTile(
                  leading: Icon(Icons.folder, color: Colors.blue), // 文件夹图标
                  title: Text(folder.name, style: TextStyle(fontSize: 16)),
                  subtitle: Text('视频数量: $videoCount'),
                  onTap: () {
                    Get.to(() => VideoListPage(pathEntity: folder));
                  },
                );
              },
            );
          },
          // separatorBuilder: (BuildContext context, int index) => Divider(), // 分隔符
        );
      }),
    );
  }
}
